import React, { useState, useEffect } from 'react';
import {
    Table,
} from 'antd';

import { request } from '../axios/http.js';


function getType(o) {
    return Object.prototype.toString.call(o).slice(8, -1);
}

function getDateString(d) {
    const pad = (i) => i.toString().padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

/**
 * 转换时间字符串
 * @param {*} a 
 * @returns {string}
 */
function formatTime(a, formatString = 'YYYY-MM-DD HH:mm:ss') {
    if (a) {
        if (a.format) {
            return a.format(formatString);
        } else {
            const d = new Date(a);
            return getDateString(d);
        }
    }
    return a;
}

/**
 * 转换响应到二进制对象
 * @param {object} response axios 响应
 * @param {string} filename 导出文件名
 */
function convertRes2Blob(response, filename = 'untitled') {
    const blob = new Blob([response], {
        type: 'application/vnd.ms-excel', // Office 2003 format
        // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // Office 2007 format
    });
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename);
    } else {
        const blobURL = window.URL.createObjectURL(blob);
        const tempLink = document.createElement('a');
        tempLink.style.display = 'none';
        tempLink.href = blobURL;
        tempLink.setAttribute('download', filename);
        if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank');
        }
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        window.URL.revokeObjectURL(blobURL);
    }
}

/**
 * 表格
 */
const BasicTable = React.memo(function BasicTable({ rowKey, pagination, ...props }) {
    const rowKeyProp = rowKey ? rowKey : (row, index) => index;
    const paginationOption = getType(pagination) === 'Object' ? {
        // showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total) => `共 ${total} 条数据`,
        ...pagination,
    } : false;

    return (
        <Table
            className="x-basictable"
            size="small"
            rowKey={rowKeyProp}
            pagination={paginationOption}
            {...props} />
    );
});


/**
 * 表格Hooks - 初始值
 */
 const initTableState = {
    data: [],
    selected: { keys: [], rows: [] },
    loading: false,
    pagination: {},
};

/**
 * 表格Hooks
 * @param {string} path 查询 URL 路径
 * @param {object} searchQuery 查询参数
 */
function useTableState(path, searchQuery) {
    const [state, setState] = useState({
        ...initTableState,
        rowSelection: {
            selectedRowKeys: [],
            onChange: (keys, rows) => {
                setState(prev => ({
                    ...prev,
                    selected: { keys, rows },
                    rowSelection: {
                        ...prev.rowSelection,
                        selectedRowKeys: keys,
                    },
                }));
            },
        },
    });
    const [query, setQuery] = useState({});
    const [init, setInit] = useState(false);

    useEffect(() => {
        setQuery(searchQuery);
    }, [searchQuery]);

    useEffect(() => {
        if (!init) {
            return;
        }
        setState(prev => ({
            ...prev,
            loading: true,
        }));
        request(path, { params: query }).then((res) => {
            setState(prev => ({
                ...prev,
                data: res.data.data,
                selected: initTableState.selected,
                loading: false,
                pagination: {
                    current: res.data.pageNum,
                    pageSize: res.data.pageSize,
                    total: res.data.total,
                    onChange(page) {
                        setQuery(prev => ({
                            ...prev,
                            pageNum: page,
                        }));
                    },
                },
                rowSelection: {
                    ...prev.rowSelection,
                    selectedRowKeys: [],
                },
            }));
        }).catch((err) => {
            err && console.error(err);
        });
    }, [path, query, init]);

    useEffect(() => {
        setInit(true);
        return () => setInit(false);
    }, []);

    return [state];
}

export {
    formatTime,
    convertRes2Blob,
    BasicTable,
    useTableState,
};
